import logging
import os

from llama_index.core import StorageContext
from llama_index.core.callbacks import EventPayload
from minio import Minio
from minio.error import MinioException

logger = logging.getLogger(__name__)

bucket_name='documents'
minioadmin = 'minioadmin'
access_key = 'minioadmin'


def get_minio_client() -> Minio:
    """
    Get a MinIO client instance.
    """
    logger.info("Creating MinIO client instance.")
    return Minio(
        '192.168.56.1:9000',
        access_key=access_key,
        secret_key=minioadmin,
        secure=False  # Set to True if using HTTPS
    )

task_id="test"
file_name='abc.txt'
temp_path='Y:\can_del\minio\knowledge.txt'
object_name='test/abc.txt'

def get_object():
    minio_client = get_minio_client()
    try:
        local_temp_path = f"/tmp/temp_{task_id}_{file_name}"  # 使用系统临时目录
        logger.info(f"Task {task_id}: Downloading file from MinIO: {temp_path} to {local_temp_path}")
        minio_client.fget_object(
            bucket_name=bucket_name,
            object_name=temp_path,
            file_path=local_temp_path
        )
        logger.info(f"Task {task_id}: File downloaded successfully")
    except MinioException as e:
        error_msg = f"Failed to download temp file: {str(e)}"
        logger.error(f"Task {task_id}: {error_msg}")
        raise Exception(error_msg)

def put_object():
    from utils import project_setting
    file_name=f'{project_setting.PROJECT_PATH}{os.sep}knowledge.txt'
    with open(file_name, 'rb') as file:
        file_size = os.path.getsize(file_name)
        # file_content = file.read()
        content_type='text/plain'

        minio_client = get_minio_client()
        minio_client.put_object(
            bucket_name=bucket_name,
            object_name=object_name,
            data=file,
            length=file_size,  # 指定文件大小
            content_type=content_type
        )


put_object()
import httpcore
# import openai
# openai
httpcore._sync.http11
# EventPayload
# from llama_index.core.base.llms.types import ChatResponse
# ChatResponse
# end_event.payload['response'].message
StorageContext